﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace CommonTool
{
    /// <summary>
    /// 序列化器
    /// </summary>
    public static class Serializer
    {
        public static byte[] BinarySerializer(object obj)
        {
            using (var ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }  
        }

        public static T BinaryDeserializer<T>(byte[] buffer)
        {
            var t = default(T);
            using (var ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                ms.Write(buffer, 0, buffer.Length);
                ms.Position = 0;
                t = (T)formatter.Deserialize(ms);
            }
            return t;
        }

        public static T Clone<T>(T t)
        {
            return BinaryDeserializer<T>(BinarySerializer(t));
        }
    }
}
